<template>
  <g-dialog
    width="50%"
    :title="getTitle"
    :visible.sync="dialogVisible"
    :isShowBtn="true"
    append-to-body
    :destroy-on-close="true"
    :beforeClose="hangleOnclose"
  >
    <div v-loading.fullscreen.lock="fullLoading">
      <el-form ref="form" :rules="rules" :model="form" label-width="100px" label-position="top">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="登录账号" prop="username">
              <el-input v-model="form.username" placeholder="请输入登录账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password" v-if="!isUpdate">
              <el-input
                type="password"
                min="6"
                maxlength="16"
                placeholder="请输入6-16位密码"
                v-model="form.password"
                show-password
              />
            </el-form-item>

            <el-form-item v-else label="设置管理员" prop="isAdmin">
              <el-switch v-model="form.isAdmin" :active-value="1" :inactive-value="0" @click="setAdmin"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realname">
              <el-input v-model="form.realname" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" maxlength="11" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" max="32" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="选择角色" prop="roles">
              <el-select v-model="form.roleId" clearable placeholder="请选择" class="w-full" @change="changeRole">
                <el-option v-for="item in roleOpts" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12" v-if="!isUpdate">
          <el-col>
            <el-form-item label="人员头像" prop="username">
              <UploadFile
                :fileList="fileList"
                :limit="1"
                :accept="limitImageType.join(',')"
                @send-file-list="getFileList"
              ></UploadFile>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="g-dialog-bottom-action">
      <el-button @click="handleClose" size="small">取消</el-button>
      <el-button type="primary" @click="handleSubmit()" size="small">提交</el-button>
    </div>
  </g-dialog>
</template>

<script>
import { addUserApi, updateUserApi, detailUserApi,setAdminApi } from '@/api/user-api';
import { getRoleApi } from '@/views/system/role/components/role.js';
import { limitImageType } from '@/libs/dict/attachement-dict';
export default {
  name: 'CreateUser',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    editId: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      limitImageType,
      localVisible: this.visible,
      fullLoading: false,
      handleThrottledSubmit: null,
      detailData: {},
      roleOpts: [],
      defaultProps: {
        value: 'id',
        label: 'name',
        checkStrictly: true, // 父子不关联
        emitPath: false, // false只返回当前节点的值 true返回节点值数组
        multiple: false // 多选
      },
      form: {
        attachement: null,
        isAdmin: 0,
        roleId: null,
        roles: [],
        realname: '',
        username: '',
        password: '',
        email: null,
        phone: null
      },
      fileList: [],
      rules: {
        username: [
          { required: true, message: '请输入人员登录账号' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符' }
        ],
        password: [
          { required: true, message: '请输入人员密码' },
          { min: 5, max: 20, message: '长度在 6 到 16 个字符' }
        ],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],

        roles: { required: true, message: '请选择角色' },
        realname: [{ min: 2, max: 30, message: '长度在 2 到 30 个字符' }]
      }
    };
  },
  computed: {
    isUpdate() {
      return Boolean(this.editId);
    },
    getTitle() {
      return this.isUpdate ? '编辑人员' : '新增人员';
    },

    dialogVisible: {
      get() {
        return this.localVisible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    }
  },

  mounted() {
    this.getRole();
    if (this.isUpdate) {
      this.getDetail();
    }
  },

  methods: {
    async getRole() {
      try {
        const {
          data: { items }
        } = await getRoleApi();
        this.roleOpts = items ?? [];
      } catch (err) {
        console.warn(err);
      }
    },

    async getDetail() {
      try {
        const { data } = await detailUserApi(this.editId);
        for (let key in this.form) {
          if (key === 'roles') continue;
          this.form[key] = data[key];
        }

        this.form.roleId = data?.roles?.[0]?.id ?? null;
      } catch (err) {
        console.warn(err);
      } finally {
        this.fullLoading = false;
      }
    },

    beforeSubmit() {
      this.form.roles = this.roleOpts.filter((r) => r.id === this.form.roleId);
      const params = {
        ...this.form
      };
      return params;
    },
    handleSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false;

        try {
          this.fullLoading = true;

          let params = this.beforeSubmit();

          let _code = 0;
          if (this.isUpdate) {
            params.id = this.editId;
            const { code } = await updateUserApi(params);
            _code = code;
          } else {
            const { code } = await addUserApi(params);
            _code = code;
          }

          if (_code === 200) {
            this.$modal.msgSuccess('操作成功');
            this.handleClose();
          }
        } catch (err) {
          console.warn(err);
        } finally {
          this.fullLoading = false;
        }
      });
    },
    // 点击icon-close触发
    hangleOnclose() {
      this.handleClose();
    },

    handleClose() {
      this.dialogVisible = false;
      this.$emit('close-create');
    },

    changeType(val) {
      this.form.order = 1;
    },
    changeMenu(val) {
      console.log(val);
    },
    changeRole(val) {},
    getFileList(files = []) {
      this.form.attachement = files?.[0];
    },

    async setAdmin(){
      try{
        const {code} = await setAdminApi({
          id: this.editId,
          isAdmin: this.form.isAdmin
        })
        if(code !== 200) return
        this.$modal.msgSuccess()
      }
      catch(err){
        console.warn(err)
      }
    }
  }
};
</script>

<style lang="scss" scoped></style>
